let ws = require("nodejs-websocket");
let protobufjs = require("protobufjs");
let root = protobufjs.loadSync("./protocol/mini_game_net.proto");   //直接使用login.proto文件

 
console.log("开始创建websocket");
let server = ws.createServer(function(conn){
    console.log("连接成功");
    conn.on("binary", function (inStream) {
        console.log("接收消息");
        let data = new Buffer(0);
        inStream.on("readable", function () {
            let newData = inStream.read();
            if (newData) {
                data = Buffer.concat([data, newData], data.length + newData.length)
            }
        })
        inStream.on("end", function () {
            console.log("Received " + data.length);
             
            // //解析接收的数据,cmd
            // let byteLength = data.readUInt16BE(0);
            // console.log("接收数据的byteLength:",byteLength);

            let cmd = data.readInt16BE(0);
            console.log("接收数据的cmd:",cmd);

            let byteLength = data.readInt16BE(2);
            console.log("接收数据的byteLength:",byteLength);

            // let byteLength = data.slice(0,2);
            // console.log("接收数据的byteLength:",byteLength,data.length);

            // let cmd = data.slice(0,2);
            // console.log("接收数据的cmd:",cmd,data.length);

            let userData = data.slice(2,data.length)

            // let bytes = Buffer.from(data,1);
            // //解析接收的数据,loginReq
            let LoginReq = root.lookupType("mini.game.net.proto.GoldChange");
            let loginReq = LoginReq.decode(userData);
            console.log("接收数据的", loginReq);
        })
        // //发送的数据,loginReq
        let sendLoginReq =  root.lookupType("mini.game.net.proto.GoldChange").create({uid:123,delta:234});
        console.log("-------------------------",sendLoginReq)
        
        let sendData = root.lookupType("mini.game.net.proto.GoldChange").encode(sendLoginReq).finish();
        // console.log("-------------------------",sendData.length)
        // //发送的数据,cmd
        // let sendBuffer1 = Buffer.alloc(2);
        // sendBuffer1.writeInt16BE(10000);

        // let sendBuffer = Buffer.alloc(2);
        // sendBuffer.writeInt16BE(sendData.length);

        // //拼接数据并发送
        // let totalBuffer = Buffer.concat([sendBuffer,sendBuffer1,sendData],sendData.length + sendBuffer1.length + sendBuffer.length);
    
        conn.send(sendData)
         
    })
    conn.on("close", function (code, reason) {
        console.log("关闭连接")
    });
    conn.on("error", function (code, reason) {
        console.log("异常关闭")
    });
}).listen(8001)
console.log("开始创建websocket完毕");